<?php

namespace addons\store\controller;

use addons\store\Store as baseStore;
use addons\store\server\Store as storeServer;
use data\service\Address;
use data\service\Order as OrderService;
use think\Validate;

/**
 * o2o门店控制器
 * Class GoodHelper
 * @package addons\store\controller
 */
class Store extends baseStore
{

    public function __construct()
    {
        parent::__construct();
    }

    /*
     * 门店列表
     */
    public function storeList()
    {
        $page_index = request()->post("page_index", 1);
        $page_size = request()->post("page_size", PAGESIZE);
        $search_text = request()->post("search_text", '');
        $status = request()->post("status", '');
        $excepted_store_id = input('post.excepted_store_id/a');
        $storeServer = new storeServer();
        $condition = array(
            'website_id' => $this->website_id,
            'shop_id' => $this->instance_id,
            'store_name' => array(
                'like',
                '%' . $search_text . '%'
            )
        );
        if ($status != '') {
            $condition['status'] = $status;
        }
        if ($excepted_store_id != '') {
            $condition['store_id'] = ['not in', $excepted_store_id];
        }
        $list = $storeServer->storeList($page_index, $page_size, $condition);
        $is_store = getAddons('store', $this->website_id);
        $addon_status['is_store'] = $is_store;
        $list['addon_status'] = $addon_status;
        return $list;
    }

    /*
     * 添加修改门店
     * **/
    public function addOrUpdateStore()
    {
        $storeServer = new storeServer();
        //验证group_shopping表
        $validate = new Validate([
            'store_name' => 'require',
            'store_tel' => 'require',
            'province_id' => 'require',
            'city_id' => 'require',
            'district_id' => 'require',
            'address' => 'require',
        ]);
        if (!$validate->check(request()->post())) {
            return ['code' => 0, 'message' => $validate->getError()];
        }
        $data['store_id'] = request()->post('store_id', 0);
        $data['store_name'] = request()->post('store_name', '');
        $data['city_id'] = request()->post('city_id', 0);
        $data['store_tel'] = request()->post('store_tel', '');
        $data['province_id'] = request()->post('province_id', 0);
        $data['district_id'] = request()->post('district_id', 0);
        $data['address'] = request()->post('address', 0);
        $data['status'] = request()->post('status', 0);
        $data['lat'] = request()->post('store_lat', 0);
        $data['lng'] = request()->post('store_lng', 0);
        $data['start_time'] = request()->post('start_time', '');
        $data['finish_time'] = request()->post('finish_time', '');
        $data['imageArray'] = request()->post('img_id_array/a', array());
        $img = '';
        if ($data['imageArray']) {
            foreach ($data['imageArray'] as $v) {
                $img .= $v . ',';
            }
        }
        $data['img_id_array'] = substr($img, 0, -1);
        $data['picture'] = $data['imageArray'][0];
        if (request()->post('store_id', 0)) {
            $ret_val = $storeServer->updateStore($data);
        } else {
            $ret_val = $storeServer->addStore($data);
        }


        if ($ret_val <= 0) {
            return AjaxReturn($ret_val);
        }
        if (request()->post('store_id', 0)) {
            $this->addUserLog('更新门店', $ret_val);
        } else {
            $this->addUserLog('添加门店', $ret_val);
        }
        return AjaxReturn(1);
    }

    /*
     * 店员列表
     */
    public function assistantList()
    {
        $page_index = request()->post("page_index", 1);
        $page_size = request()->post("page_size", PAGESIZE);
        $search_text = request()->post("search_text", '');
        $storeServer = new storeServer();
        $condition = array(
            'vsa.website_id' => $this->website_id,
            'vsa.shop_id' => $this->instance_id,
            'vsa.assistant_name' => array(
                'like',
                '%' . $search_text . '%'
            )
        );
        $list = $storeServer->assistantList($page_index, $page_size, $condition);
        return $list;
    }

    /*
     * 添加修改店员
     * **/
    public function addOrUpdateAssistant()
    {
        $storeServer = new storeServer();
        $validate_data = [
            'store_id' => 'require',
            'jobs_id' => 'require',
            'assistant_name' => 'require',
            'assistant_tel' => 'require',
        ];
        if (!request()->post('assistant_id', 0)) {
            $validate_data['password'] = 'require';
        }
        //验证assistant表
        $validate = new Validate($validate_data);
        if (!$validate->check(request()->post())) {
            return ['code' => 0, 'message' => $validate->getError()];
        }
        if (request()->post('assistant_id', 0)) {
            $ret_val = $storeServer->updateAssistant(request()->post());
        } else {
            $ret_val = $storeServer->addAssistant(request()->post());
        }
        if ($ret_val <= 0) {
            return AjaxReturn($ret_val);
        }
        if (request()->post('assistant_id', 0)) {
            $this->addUserLog('更新店员', $ret_val);
        } else {
            $this->addUserLog('添加店员', $ret_val);
        }
        return AjaxReturn(1);
    }

    /*
     * 岗位列表
     */
    public function jobsList()
    {
        $page_index = request()->post("page_index", 1);
        $page_size = request()->post("page_size", PAGESIZE);
        $search_text = request()->post("search_text", '');
        $storeServer = new storeServer();
        $condition = array(
            'website_id' => $this->website_id,
            'shop_id' => $this->instance_id,
            'jobs_name' => array(
                'like',
                '%' . $search_text . '%'
            )
        );
        $list = $storeServer->jobsList($page_index, $page_size, $condition);
        return $list;
    }

    /*
     * 添加修改岗位
     * **/
    public function addOrUpdateJobs()
    {
        $storeServer = new storeServer();
        //验证group_shopping表
        $validate = new Validate([
            'jobs_name' => 'require'
        ]);
        if (!$validate->check(request()->post())) {
            return ['code' => 0, 'message' => $validate->getError()];
        }
        //验证验证group_shopping_goods表
        if (request()->post('jobs_id', 0)) {
            $ret_val = $storeServer->updateJobs(request()->post());
        } else {
            $ret_val = $storeServer->addJobs(request()->post());
        }


        if ($ret_val <= 0) {
            return AjaxReturn($ret_val);
        }
        if (request()->post('jobs_id', 0)) {
            $this->addUserLog('更新岗位', $ret_val);
        } else {
            $this->addUserLog('添加岗位', $ret_val);
        }
        return AjaxReturn(1);
    }

    /*
     * 删除门店
     */
    public function deleteStore()
    {
        $store_id = request()->post("store_id", 0);
        if (!$store_id) {
            return AjaxReturn(0);
        }
        $storeServer = new storeServer();
        $retval = $storeServer->deleteStore($store_id);
        if ($retval <= 0) {
            return AjaxReturn($retval);
        }
        $this->addUserLog('删除门店', $retval);
        return AjaxReturn(1);
    }

    /*
     * 删除岗位
     */
    public function deleteJobs()
    {
        $jobs_id = request()->post("jobs_id", 0);
        if (!$jobs_id) {
            return AjaxReturn(0);
        }
        $storeServer = new storeServer();
        $retval = $storeServer->deleteJobs($jobs_id);
        if ($retval <= 0) {
            return AjaxReturn($retval);
        }
        $this->addUserLog('删除岗位', $retval);
        return AjaxReturn(1);
    }

    /*
     * 删除店员
     */
    public function deleteAssistant()
    {
        $assistant_id = request()->post("assistant_id", 0);
        if (!$assistant_id) {
            return AjaxReturn(0);
        }
        $storeServer = new storeServer();
        $retval = $storeServer->deleteAssistant($assistant_id);
        if ($retval <= 0) {
            return AjaxReturn($retval);
        }
        $this->addUserLog('删除店员', $retval);
        return AjaxReturn(1);
    }

    /*
     * 启用禁用店员
     */
    public function enableOrUnable()
    {
        $assistant_id = request()->post("assistant_id", 0);
        $enable = request()->post("enable", 0);
        if (!$assistant_id) {
            return AjaxReturn(0);
        }
        $storeServer = new storeServer();
        if ($enable) {
            $retval = $storeServer->enableAssistant($assistant_id);
            $operation = '启用';
        } else {
            $retval = $storeServer->unableAssistant($assistant_id);
            $operation = '禁用';
        }

        if ($retval <= 0) {
            return AjaxReturn($retval);
        }
        $this->addUserLog($operation . '店员-' . $assistant_id, $assistant_id);
        return AjaxReturn(1);
    }

    /**
     * 获取省列表
     */
    public function getProvince()
    {
        $address = new Address();
        $province_list = $address->getProvinceList();
        return $province_list;
    }

    /**
     * 获取城市列表
     *
     * @return Ambigous <multitype:\think\static , \think\false, \think\Collection, \think\db\false, PDOStatement, string, \PDOStatement, \think\db\mixed, boolean, unknown, \think\mixed, multitype:, array>
     */
    public function getCity()
    {
        $address = new Address();
        $province_id = request()->post('province_id', 0);
        $city_list = $address->getCityList($province_id);
        return $city_list;
    }

    /**
     * 获取区域地址
     */
    public function getDistrict()
    {
        $address = new Address();
        $city_id = request()->post('city_id', 0);
        $district_list = $address->getDistrictList($city_id);
        return $district_list;
    }

    /*
     * 根据店铺id获取门店列表
     */
    public function getStoreList()
    {
        $shop_id = request()->post("shop_id", 0);
        $lng = request()->post("lng", 0);
        $lat = request()->post("lat", 0);
        $store_list = request()->post("store_list");
        $storeServer = new storeServer();
        $condition = array(
            'website_id' => $this->website_id,
            'shop_id' => $shop_id,
            'status' => 1,
        );
        $place = [
            'lng' => $lng,
            'lat' => $lat
        ];
        if ($store_list) {
            $store_id = explode(',', $store_list);
            $condition['store_id'] = ['IN', $store_id];
        }
        $list = $storeServer->storeListForFront(1, 0, $condition, $place);
        return $list;
    }

    /*
     * wap根据订单id核销订单
     */
    public function pickupOrder()
    {
        $order_id = request()->post("order_id", 0);
        if (!$order_id) {
            return json(AjaxReturn(0));
        }
        $storeServer = new storeServer();
        $result = $storeServer->pickupOrder($order_id);
        if (!$result) {
            return json(AjaxReturn(0));
        }
        return json(['code' => 1, 'message' => '操作成功']);
    }

    /*
     * wap根据核销码获取订单信息
     */
    public function getOrderListByCode()
    {
        $code = request()->post("code", 0);
        if (!$code) {
            return json(AjaxReturn(0));
        }
        $condition['is_deleted'] = 0; // 未删除订单
        $condition['website_id'] = $this->website_id;
        $condition['shop_id'] = $this->instance_id;
        $condition['verification_code'] = $code;
        $order_service = new OrderService();
        $list = $order_service->getOrderList(1, 0, $condition, 'create_time DESC');
        $order_list = [];
        foreach ($list['data'] as $k => $order) {
            $order_list[$k]['order_id'] = $order['order_id'];
            $order_list[$k]['order_no'] = $order['order_no'];
            $order_list[$k]['out_order_no'] = $order['out_trade_no'];
            $order_list[$k]['shop_id'] = $order['shop_id'];
            $order_list[$k]['shop_name'] = $order['shop_name'] ?: '自营店';
            $order_list[$k]['order_money'] = $order['order_money'];
            $order_list[$k]['order_status'] = $order['order_status'];
            $order_list[$k]['status_name'] = $order['status_name'];
            $order_list[$k]['pay_type_name'] = $order['pay_type_name'];
            $order_list[$k]['is_evaluate'] = $order['is_evaluate'];
            $order_list[$k]['verification_code'] = $order['verification_code'];
            $order_list[$k]['verification_qrcode'] = __IMG($order['verification_qrcode']);
            $order_list[$k]['member_operation'] = array_merge($order['member_operation'], [['no' => 'detail', 'name' => '订单详情']]);
            $order_list[$k]['promotion_status'] = ($order['promotion_money'] + $order['coupon_money'] > 0) ?: false;

            foreach ($order['order_item_list'] as $key_sku => $item) {
                $order_list[$k]['order_item_list'][$key_sku]['order_goods_id'] = $item['order_goods_id'];
                $order_list[$k]['order_item_list'][$key_sku]['goods_id'] = $item['goods_id'];
                $order_list[$k]['order_item_list'][$key_sku]['sku_id'] = $item['sku_id'];
                $order_list[$k]['order_item_list'][$key_sku]['goods_name'] = $item['goods_name'];
                $order_list[$k]['order_item_list'][$key_sku]['price'] = $item['price'];
                $order_list[$k]['order_item_list'][$key_sku]['num'] = $item['num'];
                $order_list[$k]['order_item_list'][$key_sku]['pic_cover'] = getApiSrc($item['picture']['pic_cover']);
                $order_list[$k]['order_item_list'][$key_sku]['spec'] = $item['spec'];
                $order_list[$k]['order_item_list'][$key_sku]['status_name'] = $item['status_name'];
                $order_list[$k]['order_item_list'][$key_sku]['refund_status'] = $item['refund_status'];
            }

            // 当订单需要进行整单售后时，这个字段取订单商品第一个商品的售后状态（目前正确情况，所有商品的refund_status一样），用于判断整单售后操作
            $order_list[$k]['order_refund_status'] = reset($order_list[$k]['order_item_list'])['refund_status'];

        }

        return json([
            'code' => 1,
            'message' => '获取成功',
            'data' => [
                'order_list' => $order_list,
            ]
        ]);
    }

    /*
     * wap获取门店订单
     */
    public function getStoreOrderList()
    {
        $store_id = request()->post("store_id", 0);
        $page_index = request()->post('page_index', 1);
        $page_size = request()->post('page_size') ?: PAGESIZE;
        $order_status = request()->post('order_status');
        $search_text = request()->post('search_text');
        if (!$store_id) {
            return json(AjaxReturn(0));
        }
        $condition['is_deleted'] = 0; // 未删除订单
        $condition['website_id'] = $this->website_id;
        $condition['shop_id'] = $this->instance_id;
        $condition['store_id'] = $store_id;
        $condition['shipping_type'] = 2;
        if (is_numeric($search_text)) {
            $condition['order_no'] = ['LIKE', '%' . $search_text . '%'];
        } elseif (!empty($search_text)) {
            $condition['or'] = true;
            $condition['goods_name'] = ['LIKE', '%' . $search_text . '%'];
        }
        if ($order_status != '') {
            // $order_status 1 待提货
            if ($order_status == 1) {
                // 订单状态为待发货实际为已经支付未完成还未发货的订单
                $condition['shipping_status'] = 0; // 0 待提货
                $condition['pay_status'] = 2; // 2 已支付
                $condition['order_status'][] = ['neq', 4]; // 4 已完成
                $condition['order_status'][] = ['neq', 5]; // 5 关闭订单
                $condition['order_status'][] = ['neq', -1]; // -1 售后订单
            } else {
                $condition['order_status'] = $order_status;
            }
        }
        $order_service = new OrderService();
        $list = $order_service->getOrderList($page_index, $page_size, $condition, 'create_time DESC');
        $order_list = [];
        foreach ($list['data'] as $k => $order) {
            $order_list[$k]['order_id'] = $order['order_id'];
            $order_list[$k]['order_no'] = $order['order_no'];
            $order_list[$k]['out_order_no'] = $order['out_trade_no'];
            $order_list[$k]['shop_id'] = $order['shop_id'];
            $order_list[$k]['shop_name'] = $order['shop_name'] ?: '自营店';
            $order_list[$k]['order_money'] = $order['order_money'];
            $order_list[$k]['order_status'] = $order['order_status'];
            $order_list[$k]['status_name'] = $order['status_name'];
            $order_list[$k]['pay_type_name'] = $order['pay_type_name'];
            $order_list[$k]['is_evaluate'] = $order['is_evaluate'];
            $order_list[$k]['member_operation'] = array_merge($order['member_operation'], [['no' => 'detail', 'name' => '订单详情']]);
            $order_list[$k]['promotion_status'] = ($order['promotion_money'] + $order['coupon_money'] > 0) ?: false;

            foreach ($order['order_item_list'] as $key_sku => $item) {
                $order_list[$k]['order_item_list'][$key_sku]['order_goods_id'] = $item['order_goods_id'];
                $order_list[$k]['order_item_list'][$key_sku]['goods_id'] = $item['goods_id'];
                $order_list[$k]['order_item_list'][$key_sku]['sku_id'] = $item['sku_id'];
                $order_list[$k]['order_item_list'][$key_sku]['goods_name'] = $item['goods_name'];
                $order_list[$k]['order_item_list'][$key_sku]['price'] = $item['price'];
                $order_list[$k]['order_item_list'][$key_sku]['num'] = $item['num'];
                $order_list[$k]['order_item_list'][$key_sku]['pic_cover'] = getApiSrc($item['picture']['pic_cover']);
                $order_list[$k]['order_item_list'][$key_sku]['spec'] = $item['spec'];
                $order_list[$k]['order_item_list'][$key_sku]['status_name'] = $item['status_name'];
                $order_list[$k]['order_item_list'][$key_sku]['refund_status'] = $item['refund_status'];
            }

            // 当订单需要进行整单售后时，这个字段取订单商品第一个商品的售后状态（目前正确情况，所有商品的refund_status一样），用于判断整单售后操作
            $order_list[$k]['order_refund_status'] = reset($order_list[$k]['order_item_list'])['refund_status'];

        }

        return json([
            'code' => 1,
            'message' => '获取成功',
            'data' => [
                'order_list' => $order_list,
                'page_count' => $list['page_count'],
                'total_count' => $list['total_count']
            ]
        ]);
    }

    /*
     * wap根据店铺id获取门店列表
     */
    public function getStoreListForWap()
    {
        $order = request()->post('order');
        $sort = request()->post('sort') ?: 'DESC';
        $search_text = request()->post('search_text');
        $shop_id = request()->post("shop_id", 0);
        $lng = request()->post("lng", '');
        $lat = request()->post("lat", '');
        $page_index = request()->post("page_index", 1);
        $page_size = request()->post("page_size", 0);

        $storeServer = new storeServer();
        $condition = array(
            'website_id' => $this->website_id,
            'shop_id' => $shop_id,
            'status' => 1,
        );

        //模糊搜索门店
        if ($search_text) {
            $condition['store_name'] = ['LIKE', $search_text . '%'];
        }

        $place = [
            'lng' => $lng,
            'lat' => $lat
        ];

        $list = $storeServer->storeListForFront($page_index, $page_size, $condition, $place);

        //按距离排序
        if ($order == 'distance' && $sort == 'DESC') {
            array_multisort(array_column($list['store_list'], 'distance'), SORT_DESC, $list['store_list']);
        }
        if ($order == 'distance' && $sort == 'ASC') {
            array_multisort(array_column($list['store_list'], 'distance'), SORT_ASC, $list['store_list']);
        }

        //按人气排序
        if ($order == 'score' && $sort == 'DESC') {
            array_multisort(array_column($list['store_list'], 'score'), SORT_DESC, $list['store_list']);
        }
        if ($order == 'score' && $sort == 'ASC') {
            array_multisort(array_column($list['store_list'], 'score'), SORT_ASC, $list['store_list']);
        }

        //按销量排序
        if ($order == 'sales' && $sort == 'DESC') {
            array_multisort(array_column($list['store_list'], 'total_sales'), SORT_DESC, $list['store_list']);
        }
        if ($order == 'sales' && $sort == 'ASC') {
            array_multisort(array_column($list['store_list'], 'total_sales'), SORT_ASC, $list['store_list']);
        }

        if (!$list) {
            return json(AjaxReturn(0));
        }
        return json(['code' => 1, 'message' => '获取成功', 'data' => $list]);
    }

    /*
     * wap获取平台下所有门店列表
     */
    public function getAllStoreListForWap()
    {
        $order = request()->post('order');
        $sort = request()->post('sort') ?: 'DESC';
        $search_text = request()->post('search_text');
        $lng = request()->post("lng", '');
        $lat = request()->post("lat", '');
        $page_index = request()->post("page_index", 1);
        $page_size = request()->post("page_size", 0);

        $storeServer = new storeServer();
        $condition = array(
            'website_id' => $this->website_id,
            'status' => 1,
        );

        //模糊搜索门店
        if ($search_text) {
            $condition['store_name'] = ['LIKE', $search_text . '%'];
        }

        $place = [
            'lng' => $lng,
            'lat' => $lat
        ];

        $list = $storeServer->storeListForFront($page_index, $page_size, $condition, $place);

        //按距离排序
        if ($order == 'distance' && $sort == 'DESC') {
            array_multisort(array_column($list['store_list'], 'distance'), SORT_DESC, $list['store_list']);
        }
        if ($order == 'distance' && $sort == 'ASC') {
            array_multisort(array_column($list['store_list'], 'distance'), SORT_ASC, $list['store_list']);
        }

        //按人气排序
        if ($order == 'score' && $sort == 'DESC') {
            array_multisort(array_column($list['store_list'], 'score'), SORT_DESC, $list['store_list']);
        }
        if ($order == 'score' && $sort == 'ASC') {
            array_multisort(array_column($list['store_list'], 'score'), SORT_ASC, $list['store_list']);
        }

        //按销量排序
        if ($order == 'sales' && $sort == 'DESC') {
            array_multisort(array_column($list['store_list'], 'total_sales'), SORT_DESC, $list['store_list']);
        }
        if ($order == 'sales' && $sort == 'ASC') {
            array_multisort(array_column($list['store_list'], 'total_sales'), SORT_ASC, $list['store_list']);
        }

        if (!$list) {
            return json(AjaxReturn(0));
        }
        return json(['code' => 1, 'message' => '获取成功', 'data' => $list]);
    }

    /*
     * wap获取操作台权限
     */
    public function getStoreModule()
    {
        $lng = request()->post("lng", '');
        $lat = request()->post("lat", '');
        $storeServer = new storeServer();
        $condition = array(
            'website_id' => $this->website_id,
            'status' => 1,
        );
        $place = [
            'lng' => $lng,
            'lat' => $lat
        ];
        $list = $storeServer->storeListForFront(1, 0, $condition, $place);
        if (!$list) {
            return json(AjaxReturn(0));
        }
        return json(['code' => 1, 'message' => '获取成功', 'data' => $list]);
    }

    /*
     * 获取门店配置
     */
    public function getStoreSet()
    {
        $storeServer = new storeServer();
        $data = $storeServer->getStoreSet();
        return $data;
    }

    /*
     * 获取门店配置
     */
    public function storeSet()
    {
        $data = request()->post();
        $storeServer = new storeServer();
        $res = $storeServer->storeSet($data);
        return AjaxReturn($res);
    }

}
